package com.yx.cloud.activity;

import android.animation.Animator;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.SetAreaParam;
import com.yx.cloud.R;
import com.yx.cloud.animator.RestrictAreaSetHelpDialog;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.RestrictedEditActivityBinding;
import com.yx.cloud.map.YXMapView;
import com.yx.cloud.map.callback.PowerCoveredCallback;
import com.yx.cloud.map.layer.YXAreaLayer;
import com.yx.cloud.map.layer.YXCleanAreaLayer;
import com.yx.cloud.map.layer.YXForbiddenAreaLayer;
import com.yx.cloud.map.layer.YXForbiddenLineLayer;
import com.yx.cloud.map.layer.YXForbiddenMopAreaLayer;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.CommonConfirmDialog;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.iot.product.sweeper.bean.AreaInfo;
import com.iot.common.utils.Event;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

/**
 * 禁区操作界面
 */
public class RestrictedAreaSettingActivity extends BaseActivity implements View.OnClickListener {
    private static String TAG = "RestrictedAreaSettingActivity";

    private LoadProgressDialog loadProgressDialog;
    private static final int MAX_COUNT = 10;
    private boolean saving = false;
    private YXMapView yxMapView;
    private RestrictedEditActivityBinding binding;
    private PopupWindow popupWindow;

    @Override
    public void onCreate() {
         binding = RestrictedEditActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        initView();
        initData();
    }

    private void initData() {
        binding.ivRestrictedAreaReturn.setOnClickListener(this);
        binding.rlRestrictModeSelect.setOnClickListener(this);
        binding.rbNogo.setOnClickListener(this);
        binding.rbGomop.setOnClickListener(this);
        binding.rlRestrictArea.setOnClickListener(this);
        binding.rlRestrictLine.setOnClickListener(this);
        binding.ivRestrictedAreaSave.setOnClickListener(this);
        binding.ivRestrictHelp.setOnClickListener(this);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                initLoadingDialog();
                loadProgressDialog.show();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (binding.tvRestrictMode.getText().equals(getString(R.string.MM_NoGo))) {
            yxMapView.setForbiddenAreaEditable(true);
            yxMapView.setForbiddenMopAreaEditable(false);
            yxMapView.setForbiddenLineEditable(true);
        } else if (binding.tvRestrictMode.getText().equals(getString(R.string.MM_NoMop))) {
            yxMapView.setForbiddenAreaEditable(false);
            yxMapView.setForbiddenMopAreaEditable(true);
            yxMapView.setForbiddenLineEditable(false);
        }

        yxMapView.showPowerProtectArea(true);
        yxMapView.setPowerCoveredCallback(powerCoveredCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        yxMapView.setForbiddenAreaEditable(false);
        yxMapView.setForbiddenMopAreaEditable(false);
        yxMapView.setForbiddenLineEditable(false);
        yxMapView.showPowerProtectArea(false);
        yxMapView.setPowerCoveredCallback(null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_SET_AREA_SUCCESS:
                if (saving) {
                    handler.removeMessages(1);
                    loadProgressDialog.dismiss();
                    ToastUtil.show(RestrictedAreaSettingActivity.this, getString(R.string.MM_T_NoGoSaved_Ok), Toast.LENGTH_LONG);
                    yxMapView.resetForbiddenAreaChangeState();
                    yxMapView.clearLayerFocus();
                    saving = false;
                    Intent_utils.backIntent(RestrictedAreaSettingActivity.this);
                }
                break;
            default:
                break;
        }
    }

    private void startLoadingAnimator(long delay) {
        handler.sendEmptyMessageDelayed(1, delay);
    }

    private void initView() {
        yxMapView = findViewById(R.id.targetView);
        yxMapView.setBackgroundColor(getResources().getColor(R.color.background_color));
        yxMapView.initMap(AppContext.get().getCurrentDevice().getMap());
        JSONObject productConfig=  AppContext.getConfig();
        yxMapView.setPowerProtectAreaSize((float) productConfig.optDouble(ProductConfigConstants.powerProtectAreaSize));
        initLoadingDialog();
    }

    private void initLoadingDialog() {

        loadProgressDialog = new LoadProgressDialog(this);

        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                Log.i(TAG, "动画执行完毕--------------------------------------------- : ");
                ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.U_T_NetworkTimeout);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

    // 捕获返回键的方法2
    @Override
    public void onBackPressed() {
        if (yxMapView.isForbiddenAreaChange()) {
            CommonConfirmDialog.newBuilder()
                    .context(this)
                    .message(getString(R.string.MM_NoGoSet_NoSave))
                    .viewId(R.layout.content_centered_dialog)
                    .confirmCallback(new CommonConfirmDialog.ConfirmCallback() {
                        @Override
                        public boolean onConfirm() {
                            //判断是否靠近电源
                            if (yxMapView.isPowerCovered()) {
                                ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoGoSet_No);
                                return true;
                            }
                            List<AreaInfo> areaInfos = new ArrayList<>();
                            List<YXAreaLayer> yxAreaLayers = yxMapView.getAreaLayerListByType(YXForbiddenAreaLayer.class, YXForbiddenLineLayer.class, YXForbiddenMopAreaLayer.class, YXCleanAreaLayer.class);
                            for (int i = 0; i < yxAreaLayers.size(); i++) {
                                AreaInfo areaInfo = yxAreaLayers.get(i).getAreaInfo();
                                areaInfos.add(areaInfo);
                            }
                            SetAreaParam setAreaParam = new SetAreaParam();
                            setAreaParam.setAreaList(areaInfos);
                            AppContext.getProductService().setArea(setAreaParam);
                            Intent_utils.backIntent(RestrictedAreaSettingActivity.this);
                            return true;
                        }

                        @Override
                        public boolean onCancel() {
                            //do nothing
                            Intent_utils.backIntent(RestrictedAreaSettingActivity.this);
                            return true;
                        }
                    }).build().show();
        } else {
            Intent_utils.backIntent(RestrictedAreaSettingActivity.this);
        }
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_restricted_area_return:
                if (yxMapView.isForbiddenAreaChange()) {
                    CommonConfirmDialog.newBuilder()
                            .context(this)
                            .message(getString(R.string.MM_NoGoSet_NoSave))
                            .viewId(R.layout.content_centered_dialog)
                            .confirmCallback(new CommonConfirmDialog.ConfirmCallback() {
                                @Override
                                public boolean onConfirm() {
                                    //判断是否靠近电源
                                    if (yxMapView.isPowerCovered()) {
                                        ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoGoSet_No);
                                        return true;
                                    }
                                    saveRestrict();
                                    return true;
                                }

                                @Override
                                public boolean onCancel() {
                                    //do nothing
                                    Intent_utils.backIntent(RestrictedAreaSettingActivity.this);
                                    return true;
                                }
                            }).build().show();
                } else {
                    Intent_utils.backIntent(RestrictedAreaSettingActivity.this);
                }
                break;
            case R.id.rl_restrict_area:
                if (binding.tvRestrictMode.getText().toString().equals(getString(R.string.MM_NoGo))) {
                    if (yxMapView.getForbiddenAreaLayers().size() >= MAX_COUNT) {
                        ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoGoFull);
                    } else {
                        yxMapView.addTempAreaLayer(YXForbiddenAreaLayer.class);
                    }

                } else if (binding.tvRestrictMode.getText().toString().equals(getString(R.string.MM_NoMop))) {
                    if (yxMapView.getForbiddenMopAreaLayers().size() >= MAX_COUNT) {
                        ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoMopFull);
                    } else {
                        yxMapView.addTempAreaLayer(YXForbiddenMopAreaLayer.class);
                    }
                }
                break;
            case R.id.rl_restrict_line:
                if (yxMapView.getForbiddenLineLayers().size() >= MAX_COUNT) {
                    ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoGoLineFull);
                } else {
                    yxMapView.addTempAreaLayer(YXForbiddenLineLayer.class);
                }
                break;
            case R.id.iv_restricted_area_save:
                //判断是否靠近电源
                if (yxMapView.isPowerCovered()) {
                    ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoGoSet_No);
                    break;
                }
                saveRestrict();
                break;
            case R.id.rl_restrict_mode_select:
                showPopupWindow();
                break;
            case R.id.iv_restrict_help:
                RestrictAreaSetHelpDialog.newBuilder()
                        .context(this)
                        .viewId(R.layout.restrict_area_set_help_dialog)
                        .confirmCallback(new RestrictAreaSetHelpDialog.ConfirmCallback() {
                            @Override
                            public boolean onConfirm() {
                                return true;
                            }

                            @Override
                            public boolean onCancel() {
                                return true;
                            }
                        }).build().show();
                break;
            default:
                break;
        }
    }

    private void saveRestrict() {
        List<AreaInfo> areaInfos = new ArrayList<>();
        List<YXAreaLayer> yxAreaLayers = yxMapView.getAreaLayerListByType(YXForbiddenAreaLayer.class, YXForbiddenLineLayer.class, YXForbiddenMopAreaLayer.class, YXCleanAreaLayer.class);
        for (int i = 0; i < yxAreaLayers.size(); i++) {
            AreaInfo areaInfo = yxAreaLayers.get(i).getAreaInfo();
            areaInfos.add(areaInfo);
        }
        SetAreaParam setAreaParam = new SetAreaParam();
        setAreaParam.setAreaList(areaInfos);
        AppContext.getProductService().setArea(setAreaParam);
        saving = true;
        startLoadingAnimator(500);
    }

    private void showPopupWindow() {
        if(popupWindow == null){
            View inflate = LayoutInflater.from(this).inflate(R.layout.restrict_edit_spinner, null);
            popupWindow = new PopupWindow(inflate, GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT);

            int[] location = new int[2];
            binding.rlRestrictModeSelect.getLocationOnScreen(location);//得到相对当前控件的坐标位置
            LinearLayout ll_nogo = inflate.findViewById(R.id.ll_nogo);
            LinearLayout ll_nomop = inflate.findViewById(R.id.ll_nomop);
            ll_nogo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (RomUtils.isFastClick()) {
                        return;
                    }
                    popupWindow.dismiss();
                    binding.tvRestrictMode.setText(getString(R.string.MM_NoGo));
                    binding.rlRestrictLine.setVisibility(View.VISIBLE);
                    binding.tvRestrictLine.setEnabled(true);
                    binding.ivRestrictLine.setEnabled(true);
                    binding.rlRestrictLine.setEnabled(true);
                    yxMapView.setForbiddenAreaEditable(true);
                    yxMapView.setForbiddenMopAreaEditable(false);
                    yxMapView.setForbiddenLineEditable(true);
                }
            });
            ll_nomop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (RomUtils.isFastClick()) {
                        return;
                    }
                    popupWindow.dismiss();
                    binding.tvRestrictMode.setText(getString(R.string.MM_NoMop));
                    binding.rlRestrictLine.setVisibility(View.GONE);
                    binding.tvRestrictLine.setEnabled(false);
                    binding.ivRestrictLine.setEnabled(false);
                    binding.rlRestrictLine.setEnabled(false);
                    yxMapView.setForbiddenAreaEditable(false);
                    yxMapView.setForbiddenMopAreaEditable(true);
                    yxMapView.setForbiddenLineEditable(false);
                }
            });
        }
        /**
         * 实例popupWindow对象
         */

        int height = (binding.rlRestrictModeSelect.getHeight() * 3 + 20 ) *  -1;
        Log.d("popHeight","height is " + height);
        //设置popupWindow显示的位置
        if(popupWindow.isShowing()){
            popupWindow.dismiss();
        }else {
            popupWindow.showAsDropDown(binding.rlRestrictModeSelect, 0, height);
        }
    }

    PowerCoveredCallback powerCoveredCallback = new PowerCoveredCallback() {
        @Override
        public void onPowerCovered() {
            ToastUtil.showShort(RestrictedAreaSettingActivity.this, R.string.MM_T_NoGoSet_No);
        }
    };

}
